from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:8848@localhost/python_web'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'your_secret_key_here'  # Replace 'your_secret_key_here' with a real secret key

db = SQLAlchemy(app)

class Student(db.Model):
    __tablename__ = 'student'
    Sno = db.Column(db.String(20), primary_key=True)
    Sname = db.Column(db.String(20), nullable=False)
    Ssex = db.Column(db.String(20), nullable=False)
    Sage = db.Column(db.Integer, nullable=False)
    Dno = db.Column(db.String(20), nullable=False)
    Sclass = db.Column(db.String(20), nullable=True)
    address = db.Column(db.String(255), nullable=True)

@app.route('/')
def index():
    students = Student.query.all()
    return render_template('index.html', students=students)

@app.route('/add', methods=['GET', 'POST'])
def add_student():
    if request.method == 'POST':
        new_student = Student(
            Sno=request.form['Sno'],
            Sname=request.form['Sname'],
            Ssex=request.form['Ssex'],
            Sage=request.form['Sage'],
            Dno=request.form['Dno'],
            Sclass=request.form['Sclass'],
            address=request.form['address']
        )
        db.session.add(new_student)
        db.session.commit()
        flash('Student added successfully!')
        return redirect(url_for('index'))
    else:
        # 如果是 GET 请求，显示添加学生的表单
        return render_template('add_student.html')
@app.route('/edit_student/<Sno>', methods=['GET', 'POST'])
def edit_student(Sno):
    student = Student.query.filter_by(Sno=Sno).first()
    if not student:
        flash('Student not found!')
        return redirect(url_for('index'))
    if request.method == 'POST':
        student.Sname = request.form['Sname']
        student.Ssex = request.form['Ssex']
        student.Sage = request.form['Sage']
        student.Dno = request.form['Dno']
        student.Sclass = request.form['Sclass']
        student.address = request.form['address']
        db.session.commit()
        flash('Student updated successfully!')
        return redirect(url_for('index'))
    return render_template('edit_student.html', student=student)

@app.route('/delete_student/<Sno>', methods=['GET', 'POST'])
def delete_student(Sno):
    student = Student.query.filter_by(Sno=Sno).first()
    if not student:
        flash('Student not found!')
        return redirect(url_for('index'))

    if request.method == 'POST':
        db.session.delete(student)
        db.session.commit()
        flash('Student deleted successfully!')
        return redirect(url_for('index'))

    # 如果是 GET 请求，显示确认删除的表单
    return render_template('delete_student.html', student=student)

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)